package com.zfzs.post.common.security;

import com.zfzs.post.common.bean.ResponseCode;
import com.zfzs.post.common.utils.JwtTokenUtil;
import com.zfzs.post.service.JwtUserDetailsService;
import com.zfzs.post.service.RedisService;
import com.zfzs.post.common.bean.ResponseCode;
import com.zfzs.post.common.utils.JwtTokenUtil;
import com.zfzs.post.service.JwtUserDetailsService;
import com.zfzs.post.common.utils.JwtTokenUtil;
import io.jsonwebtoken.ExpiredJwtException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.web.authentication.WebAuthenticationDetailsSource;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
* 拦截器  校验需要登录的token
* @author: ck
* @create: 2019/8/8/17:02
**/
@Slf4j
@Component
public class JwtAuthorizationTokenFilter extends OncePerRequestFilter {

    private final UserDetailsService userDetailsService;

    private final JwtTokenUtil jwtTokenUtil;

    private final String tokenHeader;

    @Autowired
    private JwtUserDetailsService jwtUserDetailsService;

    @Autowired
    private RedisService redisService;

    public JwtAuthorizationTokenFilter(@Qualifier("jwtUserDetailsService") UserDetailsService userDetailsService, JwtTokenUtil jwtTokenUtil, @Value("${jwt.header}") String tokenHeader) {
        this.userDetailsService = userDetailsService;
        this.jwtTokenUtil = jwtTokenUtil;
        this.tokenHeader = tokenHeader;
    }

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws ServletException, IOException {
        final String requestHeader = request.getHeader(this.tokenHeader);
        String username = null;
        String authToken = null;
        if (requestHeader != null && requestHeader.startsWith("Bearer ")) {
            //查询token是否存在缓存中
            authToken = requestHeader.substring(7);
            if(!jwtUserDetailsService.isToken(authToken)){
                request.setAttribute("code",ResponseCode.LOGIN_TIME_OUT_FAIL.code);
                request.setAttribute("msg",ResponseCode.LOGIN_TIME_OUT_FAIL.msg);
            }
            try {
                username = jwtTokenUtil.getUsernameFromToken(authToken);
            } catch (ExpiredJwtException e) {
                //缓存过期
                log.error(e.getMessage());
                request.setAttribute("code",ResponseCode.TOKEN_TIME_OUT_FAIL.code);
                request.setAttribute("msg",ResponseCode.TOKEN_TIME_OUT_FAIL.msg);
            } catch (Exception ex){
                request.setAttribute("code",ResponseCode.TOKEN_ANALYSIS_FAIL.code);
                request.setAttribute("msg",ResponseCode.TOKEN_ANALYSIS_FAIL.msg);
                log.error(ex.getMessage());
            }
        }
        if (username != null && SecurityContextHolder.getContext().getAuthentication() == null) {
            JwtUser userDetails = (JwtUser)this.userDetailsService.loadUserByUsername(username);
            if(userDetails.getAgent().getIsEnabled()){
                request.setAttribute("code",ResponseCode.USER_ENABLED_FAIL.code);
                request.setAttribute("msg",ResponseCode.USER_ENABLED_FAIL.msg);
            }
            // 校验是否失效 修改密码之后需要重新登录
            if (jwtTokenUtil.validateToken(authToken, userDetails)) {
                UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(userDetails, null, userDetails.getAuthorities());
                authentication.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));
                SecurityContextHolder.getContext().setAuthentication(authentication);
            }

        }
        chain.doFilter(request, response);
    }
}
